from flask import Flask, request, render_template, make_response
from time import time, sleep
from json import dumps, loads
from os import path
from hashlib import sha256
app = Flask(__name__)

file_dir = path.dirname(__file__)

def generate_blog_tittle_list():
    try:
        with open(f'{file_dir}/databases/blog.json', 'r') as file:
            blog_db = file.read()
            json_db = loads(blog_db)
            l = json_db.values()
            tittles = []
            for item in l:
                if item != json_db['len']:
                    tittles.append(item[0])
            return tittles
    except KeyError:
        return 'Error'
    except:
        return 'Error'

def generate_new_blog_tittle_list():
    blog_tittle_list = generate_blog_tittle_list()[-5:]
    blog_tittle_list.reverse()
    tittles = []
    for item in blog_tittle_list:
        old = item
        item = item[:6]
        if item != old:
            item += '...'
        tittles.append(item)
    return tittles

def generate_blog_id_list():
    try:
        with open(f'{file_dir}/databases/blog.json', 'r') as file:
            blog_db = file.read()
            json_db = loads(blog_db)
        del json_db['len']
        l = list(json_db.keys())
        return l
    except KeyError:
        return 'Error'
    except:
        return 'Error'
    
def generate_new_blog_id_list():
    blog_id_list = generate_blog_id_list()[-5:]
    blog_id_list.reverse()
    return blog_id_list


def generate_word_tittle_list():
    try:
        with open(f'{file_dir}/databases/word.json', 'r') as file:
            word_db = file.read()
            json_db = loads(word_db)
            l = json_db.values()
            tittles = []
            for item in l:
                if item != json_db['len']:
                    tittles.append(f'{item[1]} {item[2]}')
            return tittles
    except KeyError:
        return 'Error'
    except:
        return 'Error'

def generate_word_id_list():
    try:
        with open(f'{file_dir}/databases/word.json', 'r') as file:
            word_db = file.read()
            json_db = loads(word_db)
        del json_db['len']
        l = list(json_db.keys())
        return l
    except KeyError:
        return 'Error'
    except:
        return 'Error'


@app.route("/")
def index():
    return render_template('index.html', blog_id_list=generate_new_blog_id_list(), blog_tittle_list=generate_new_blog_tittle_list())

@app.route("/en/<page>")
def english(page):
    if page == 'index':
        return render_template('en/index_en.html', blog_id_list=generate_new_blog_id_list(), blog_tittle_list=generate_new_blog_tittle_list())
    elif page == 'blog':
        return render_template('en/blog_en.html', blog_id_list=generate_blog_id_list(), blog_tittle_list=generate_blog_tittle_list())
    elif page == 'word':
        return render_template('en/word_en.html')
    #elif...
    else:
        return render_template('error.html', code='404 Not Found', text=f'No page name is {page}.'), 404


@app.route("/blog")
def blog():
    return render_template('blog.html', blog_id_list=generate_blog_id_list(), blog_tittle_list=generate_blog_tittle_list())

@app.route("/blog/<int:blog_id>")
def blog_page(blog_id):
    try:
        blog_id = str(blog_id)
        with open(f'{file_dir}/databases/blog.json', 'r') as file:
            blog_db = file.read()
            json_db = loads(blog_db)
            blog_tittle = json_db[blog_id][0]
            blog_text = json_db[blog_id][1]
    except KeyError:
        return render_template('error.html', code='404 Not Found', text=f'No blog id is {blog_id}'), 404
    except:
        return render_template('error.html', code='500 Internal Server Error', text='Server Error.'), 500
    return render_template('blog_template.html', blog_tittle=blog_tittle, blog_text=blog_text)

@app.route("/admin")
def admin():
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            return render_template('admin.html', 
                                   blog_id_list=generate_blog_id_list(), 
                                   blog_tittle_list=generate_blog_tittle_list(),
                                   
                                   word_id_list=generate_word_id_list(),
                                   word_tittle_list=generate_word_tittle_list()
                                   )
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401     

@app.route("/newblog", methods=['POST'])
def newblog():
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            blog_tittle = request.form.get('blog_tittle')
            blog_text = request.form.get('blog_text')
            with open(f'{file_dir}/databases/blog.json', 'r') as file:
                blog_db = file.read()
                json_db = loads(blog_db)
            db_len = json_db['len']
            json_db[str(db_len+1)] = [blog_tittle, blog_text]
            json_db['len'] = db_len + 1
            blog_db = dumps(json_db)
            with open(f'{file_dir}/databases/blog.json', 'w') as file:
                file.write(blog_db)
            return render_template('blog_template.html', blog_tittle=blog_tittle, blog_text=blog_text)
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401   
    
@app.route("/deleteblog", methods=['POST'])
def delete_blog():
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            blog_id = request.get_json('blog_id')
            blog_id = str(blog_id['blog_id'])
            with open(f'{file_dir}/databases/blog.json', 'r') as file:
                blog_db = file.read()
                json_db = loads(blog_db)
            del json_db[blog_id]
            blog_db = dumps(json_db)
            with open(f'{file_dir}/databases/blog.json', 'w') as file:
                file.write(blog_db)
            return render_template('blog.html', blog_id_list=generate_blog_id_list(), blog_tittle_list=generate_blog_tittle_list())
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401        

@app.route("/editblog/<int:blog_id>")
def edit_blog(blog_id):
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            blog_id = str(blog_id)
            with open(f'{file_dir}/databases/blog.json', 'r') as file:
                blog_db = file.read()
                json_db = loads(blog_db)
            blog_tittle = json_db[blog_id][0]
            blog_text = json_db[blog_id][1]
            return render_template('edit_blog.html', blog_tittle=blog_tittle, blog_text=blog_text, blog_id=blog_id)
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401        

@app.route("/modifyblog/<int:blog_id>", methods=['POST'])
def modify_blog(blog_id):
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            blog_tittle = request.form.get('blog_tittle')
            blog_text = request.form.get('blog_text')
            with open(f'{file_dir}/databases/blog.json', 'r') as file:
                blog_db = file.read()
                json_db = loads(blog_db)
            json_db[blog_id] = [blog_tittle, blog_text]
            blog_db = dumps(json_db)
            with open(f'{file_dir}/databases/blog.json', 'w') as file:
                file.write(blog_db)
            return render_template('blog.html', blog_id_list=generate_blog_id_list(), blog_tittle_list=generate_blog_tittle_list())
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401        

@app.route("/word")
def word():
    return render_template('word.html')

@app.route("/postword", methods=['POST'])
def post_word():
    word_tittle = request.form.get('word_tittle')
    call_sign = request.form.get('callsign')
    word_text = request.form.get('word_text')
    try:
        with open(f'{file_dir}/databases/word.json', 'r') as file:
            word_db = file.read()
            json_db = loads(word_db)
        len = int(json_db['len'])
        len += 1
        json_db['len'] = len
        json_db[str(len)] = [time(), word_tittle, call_sign, word_text]
        word_db = dumps(json_db)
        with open(f'{file_dir}/databases/word.json', 'w') as file:
            file.write(word_db)
    except:
        return render_template('error.html', code='500 Internal Server Error', text='Server Error.'), 500
    return render_template('index.html', blog_id_list=generate_new_blog_id_list(), blog_tittle_list=generate_new_blog_tittle_list())

@app.route("/admin_verify")
def admin_verify():
    return render_template('admin_verify.html')

@app.route("/verify", methods=['POST'])
def verify():
    password = request.form.get('password')
    hash_object = sha256()
    hash_object.update(password.encode())
    hex_digest = hash_object.hexdigest()
    with open(f'{file_dir}/databases/password.txt', 'r') as file:
        hash_password = file.read()
    if hex_digest == hash_password:
        resp = make_response(
            render_template('admin.html', blog_id_list=generate_blog_id_list(), blog_tittle_list=generate_blog_tittle_list())
            )
        resp.set_cookie('usr', 'admin', max_age=7200)
        return resp
    else:
        return render_template('error.html', code='401 Unauthorized', text='Password Error.'), 401

@app.route("/clear_cookie")
def clear_cookie():
    resp = make_response(
        render_template('index.html', blog_id_list=generate_new_blog_id_list(), blog_tittle_list=generate_new_blog_tittle_list())
    )
    resp.delete_cookie("usr")
    return resp

@app.route("/showword/<int:word_id>")
def show_word(word_id):
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            try:
                word_id = str(word_id)
                with open(f'{file_dir}/databases/word.json', 'r') as file:
                    word_db = file.read()
                    json_db = loads(word_db)
                    word_tittle = json_db[word_id][1]
                    call_sign = json_db[word_id][2]
                    word_text = json_db[word_id][3]
            except KeyError:
                return render_template('error.html', code='404 Not Found', text=f'No word id is {word_id}'), 404
            except:
                return render_template('error.html', code='500 Internal Server Error', text='Server Error.'), 500
            return render_template('word_template.html', word_tittle=word_tittle, call_sign=call_sign, word_text=word_text)
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401        

@app.route("/deleteword", methods=['POST'])
def delete_word():
    cookie = request.cookies
    try:
        if cookie['usr'] == 'admin':
            word_id = request.get_json('word_id')
            word_id = str(word_id['word_id'])
            with open(f'{file_dir}/databases/word.json', 'r') as file:
                word_db = file.read()
                json_db = loads(word_db)
            del json_db[word_id]
            word_db = dumps(json_db)
            with open(f'{file_dir}/databases/word.json', 'w') as file:
                file.write(word_db)
            sleep(3)
            return render_template('admin.html', 
                                    blog_id_list=generate_blog_id_list(), 
                                    blog_tittle_list=generate_blog_tittle_list(),
                                    
                                    word_id_list=generate_word_id_list(),
                                    word_tittle_list=generate_word_tittle_list()
                                    )
        else:
            return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401
    except:
        return render_template('error.html', code='401 Unauthorized', text='Permission Died.'), 401      

@app.errorhandler(404)
def not_found(e):
    path = request.path
    return render_template('error.html', code='404 Not Found', text=f'{path} Not Found'), 404

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8099, debug=True)